package com.itheima.service.impl;

import cn.itheima.health.entity.QueryPageBean;
import cn.itheima.health.service.UserAdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.UserAdminMapper;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class UserAdminServiceImpl implements UserAdminService {

    @Autowired
    private UserAdminMapper userAdminMapper;

    @Override
    public Map findPage(QueryPageBean queryPageBean) {
        Map map = new HashMap();
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<User> list = userAdminMapper.findPage(queryPageBean.getQueryString());
        if (list != null && list.size() > 0) {
            for (User user : list) {
                Integer id = user.getId();
                List<Integer> roleIds = userAdminMapper.finUserAndRoleById(id);
                if (roleIds != null && list.size() > 0) {
                    for (Integer roleId : roleIds) {
                        String name = userAdminMapper.findRoleName(roleId);
                        Set<Role> roles = new HashSet<>();
                        Role role = new Role();
                        role.setName(name);
                        roles.add(role);
                        user.setRoles(roles);
                        System.out.println(user);
                    }
                }
            }
        }
        PageInfo<User> pageInfo = new PageInfo<>(list);
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return map;
    }

    @Override
    public void add(User user,Integer[] roleIds) {

        userAdminMapper.add(user);

        Integer userId = user.getId();

        if(roleIds!=null){
            for (Integer roleId : roleIds) {
                userAdminMapper.addUserAndRole(userId,roleId);
            }
        }
    }

    @Override
    public void edit(User user,Integer[] roleIds) {
        userAdminMapper.edit(user);

        Integer userId = user.getId();

        userAdminMapper.removeUserAndRoleByUserId(userId);

        if(roleIds!=null){
            for (Integer roleId : roleIds) {
                userAdminMapper.addUserAndRole(userId,roleId);
            }
        }
    }

    @Override
    public void deleteUserAdminById(Integer id) {
        userAdminMapper.removeUserAndRoleByUserId(id);
        userAdminMapper.deleteUserAdminById(id);
    }
}
